package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.UserException;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        List<User> users = userMapper.findPage(queryPageBean.getQueryString());

        return PageResult.builder().rows(page.getResult()).total(page.getTotal()).build();
    }

    @Override
    public User findByUserName(String username) {
        //根据用户名查询用户基本信息
        User user = userMapper.selectByUserName(username);
        if(null != user){
            //根据userid查询用户下面所有的角色
            Set<Role> roles = roleMapper.selectByUserId(user.getId());
            if(CollectionUtil.isNotEmpty(roles)){
                //循环用户所有角色查询角色对应所有的权限
                for (Role role : roles) {
                    Set<Permission> permissions = permissionMapper.selectByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public boolean add(com.itheima.pojo.User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode(password);
        user.setPassword(encode);
        int res = userMapper.add(user);

        List<Integer> roleIds = user.getRoleIds();
        Integer userId = user.getId();
        if(CollectionUtil.isNotEmpty(roleIds)){
            for (Integer roleId : roleIds) {
                userMapper.setUserAndRoleRelation(roleId,userId);
            }
        }

        return res == 1;

    }

    @Override
    public void deleteById(Integer id) throws UserException {
        int count = userMapper.findConutById(id);

        if(count>0){
            throw new UserException("存在引用 不能删除");
        }else {
            userMapper.deleteById(id);
        }
    }

    @Override
    public User findById(String id) {

        User user = userMapper.findById(id);

        return user;
    }

    @Override
    public void edit(User user) {
        String password = user.getPassword();
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode(password);
        user.setPassword(encode);

        userMapper.edit(user);

        userMapper.deleteAssociation(user.getId());

        userMapper.setUserIdAndRoleId(user.getId(),user.getRoleIds());

    }

    @Override
    public List<User> findall() {
        List<User> users = userMapper.findall();

        return users;
    }

    @Override
    public void deletebyid(Integer id) {

        userMapper.deleteAssociation(id);

        userMapper.deletebyid(id);
    }

    @Override
    public Map findbyid4updata(Integer id) {

        HashMap<String, Object> map = new HashMap<>();

        User user = userMapper.findUserById(id);

        user.setPassword("");

        List<Role> roles = roleMapper.findAll();

        List<Integer> roleIds = userMapper.findRoleIdsByUserId(id);
        user.setRoleIds(roleIds);

        map.put("user",user);
        map.put("allRoles",roles);

        return map;
    }
}
